package univ.bme.accounting.beans;

import java.io.IOException;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import univ.bme.accounting.dao.UserDAO;
import univ.bme.accounting.domain.User;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor

@SessionScoped
@ManagedBean
public class AccountingSessionBean extends MBUtils {
	
	//This is the session user
	private User user;
	
	@EJB
	private UserDAO userdao;
		
	public User getUser(){
		if(user == null){
			ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
			if(context.getUserPrincipal() != null){
				String username = context.getUserPrincipal().getName();
				
				user = userdao.findUserByUsername(username);
			}
		}
		
		return user;
	}

	public boolean isUserAdmin(){
		return getRequest().isUserInRole(User.ADMIN_ROLE);
	}
	
	public String logOut() throws IOException{
	    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
	    ec.invalidateSession();
	    return "logout";
	}
	
	public boolean isAccessForbidden(User access_user){
		if(access_user.getVisible().equals(User.NON_PUBLIC_DATA) &&
			access_user.getId() != getUser().getId() &&
			!isUserAdmin())
			return true;
		
		return false;
	}
	
}
